import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svprogresshud/flutter_svprogresshud.dart';
import 'package:goumao_app/Customs/gm_app_util.dart';
import 'package:goumao_app/Model/gm_anim_video_model.dart';
import 'package:video_player/video_player.dart';

import '../Customs/gm_native_channel.dart';
import '../Manager/gm_http_manager.dart';
import '../Manager/gm_user_manager.dart';
import '../Model/gm_anim_comment_model.dart';
import '../Model/gm_login_user.dart';

class GMAniVideoDetailApp extends StatefulWidget {
  final GMAnimData animaData;
  final int type;
  const GMAniVideoDetailApp(
      {super.key, required this.animaData, this.type = 0});

  @override
  // ignore: library_private_types_in_public_api
  _GMAniVideoDetailAppState createState() => _GMAniVideoDetailAppState();
}

class _GMAniVideoDetailAppState extends State<GMAniVideoDetailApp> {
  late VideoPlayerController _controller;
  bool startedPlaying = false;
  List<GMAnimaCommentData> commentArr = [];

  Map<int, List<Map<String, dynamic>>> gmFoodValues = {
    1: [
      {'name': '喵粮', 'price': 20, 'path': 'assets/images/gm_mm_ml_icon@2x.png'},
      {'name': '小鱼', 'price': 30, 'path': 'assets/images/gm_mm_xy_icon@2x.png'}
    ],
    2: [
      {'name': '狗粮', 'price': 20, 'path': 'assets/images/gm_mm_gl_icon@2x.png'},
      {
        'name': '大肉棒',
        'price': 30,
        'path': 'assets/images/gm_mm_drb_icon@2x.png'
      }
    ]
  };
  Future<GMAnimaCommentModel> _gmGetCommentList() async {
    var response = await GMHttpUtilTwo().post("/open/comment/list", data: {
      "page": '1',
      'size': '10',
      "id": widget.animaData.id,
      'sort': '0'
    });
    var jsonStr = json.decode(response.toString());
    var gmComment = GMAnimaCommentModel.fromJson(jsonStr);
    return gmComment;
  }

  void _gmGetComment() async {
    var response = await GMHttpUtilTwo().post("/open/comment/list", data: {
      "page": '1',
      'size': '10',
      "id": widget.animaData.id,
      'sort': '0'
    });
    var jsonStr = json.decode(response.toString());
    GMAnimaCommentModel model = GMAnimaCommentModel.fromJson(jsonStr);
    commentArr = model.data!;
    setState(() {});
  }

  @override
  void initState() {
    super.initState();
    _gmGetComment();
    print("启动启动");
    _controller = VideoPlayerController.networkUrl(Uri.parse(
      'https://file.onepetmall.com/${widget.animaData.files!.first.url!}',
    ))
      ..initialize().then((_) {
        setState(() {});
      });

    _controller.addListener(() {
      if (!_controller.value.isPlaying && startedPlaying == false) {
        started();
        print("dafdsfsdfdsfdsf");
      }
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  Future<bool> started() async {
    await _controller.initialize();
    await _controller.play();
    startedPlaying = true;
    return true;
  }

  void reportAndAddBlack(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SizedBox(
          height: 200,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              ListTile(
                leading: const Icon(Icons.report),
                title: const Text('举报'),
                onTap: () {
                  // 处理举报操作
                  Navigator.pop(context);
                  showiOSAlertDialog(context);
                },
              ),
              ListTile(
                leading: const Icon(Icons.block),
                title: const Text('拉黑'),
                onTap: () {
                  Navigator.pop(context);
                  // 处理拉黑操作
                  _showConfirmationDialog(context);
                },
              ),
              ListTile(
                leading: const Icon(Icons.cancel),
                title: const Text('取消'),
                onTap: () {
                  Navigator.pop(context);
                },
              ),
            ],
          ),
        );
      },
    );
  }

  void _showConfirmationDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('确认操作'),
          content: const Text('拉黑用户后，您将无法再接收该用户的信息。'),
          actions: <Widget>[
            TextButton(
              onPressed: () {
                Navigator.of(context).pop(); // 关闭对话框
              },
              child: const Text(
                '取消',
                style: TextStyle(
                    color: Color(0xff1a1a1a),
                    fontSize: 15,
                    fontWeight: FontWeight.w600),
              ),
            ),
            TextButton(
              onPressed: () {
                // context.pop();
                // // 在这里处理拉黑操作
                // // 添加拉黑逻辑
                Navigator.of(context).pop(); // 关闭对话框
                // 在这里添加禁止接收用户信息的逻辑
              },
              child: const Text(
                '拉黑',
                style: TextStyle(
                    color: Color(0xff999999),
                    fontSize: 15,
                    fontWeight: FontWeight.w600),
              ),
            ),
          ],
        );
      },
    );
  }

// 更多按钮点击事件
  void showiOSAlertDialog(BuildContext context) {
    final List<String> reportReasons = [
      '资料造假',
      '恶意骚扰',
      '垃圾广告',
      '色情低俗',
      '诱导欺骗',
    ];

    showCupertinoModalPopup(
      context: context,
      builder: (BuildContext context) {
        return CupertinoActionSheet(
          actions: reportReasons.map((reason) {
            return CupertinoActionSheetAction(
              child: Text(
                reason,
                style: const TextStyle(
                    color: Color(0xff333333),
                    fontSize: 15,
                    fontWeight: FontWeight.w500),
              ),
              onPressed: () {
                // Constants.app_showToast("举报已提交");
                // // 执行特定原因的操作
                Navigator.of(context).pop();
                GMAppUtil.gmToast("举报已提交");
              },
            );
          }).toList(),
          cancelButton: CupertinoActionSheetAction(
            child: const Text(
              '取消',
              style: TextStyle(
                color: Color(0xff666666),
                fontSize: 15,
              ),
            ),
            onPressed: () {
              // 取消操作
              Navigator.of(context).pop();
            },
          ),
        );
      },
    );
  }

  Widget _gmCommentListWidget(GMAnimaCommentData commentData) {
    return Container(
      padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
      child: Column(
        children: [
          Row(
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(20),
                    child: Image.network(
                      'https://file.onepetmall.com/${commentData.user!.head!}',
                      width: 40,
                      height: 40,
                      fit: BoxFit.cover,
                    ),
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                        height: 40,
                        width: ScreenUtil().screenWidth - 16 - 10 - 40 - 16,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  commentData.user!.name!,
                                  style: const TextStyle(
                                      color: Color(0xff000000),
                                      fontSize: 14,
                                      fontWeight: FontWeight.w400),
                                ),
                                Text(
                                  commentData.user!.label == null
                                      ? "初级粉丝"
                                      : commentData.user!.label!,
                                  style: const TextStyle(
                                      color: Color(0xff666666),
                                      fontSize: 12,
                                      fontWeight: FontWeight.w400),
                                )
                              ],
                            ),
                            InkWell(
                              onTap: () {
                                reportAndAddBlack(context);
                              },
                              child: Image.asset(
                                "assets/images/gm_xq_gd_btn.png",
                                width: 20,
                              ),
                            )
                          ],
                        ),
                      ),
                      const SizedBox(
                        height: 12,
                      ),
                      Text(
                        commentData.content!,
                        style: const TextStyle(
                            color: Color(0xff1a1a1a),
                            fontSize: 15,
                            fontWeight: FontWeight.w400),
                      ),
                      const SizedBox(
                        height: 6,
                      ),
                      Text(
                        commentData.time!,
                        style: const TextStyle(
                            color: Color(0xff666666), fontSize: 12),
                      )
                    ],
                  ),
                ],
              ),
            ],
          ),
          const SizedBox(
            height: 12,
          ),
          const Divider(
            height: 1,
          ),
        ],
      ),
    );
  }

  Future<void> _gmSendFoodToUser() async {
    List<Map<String, dynamic>>? gmFood = gmFoodValues[widget.type == 0 ? 1 : 2];
    int count = gmFood!.first['price'];
    SVProgressHUD.show();
    GMLoginUser user = GMUserManager().user!;
    user.coins = user.coins! - count;
    await GMUserManager().saveUser(user);
    Future.delayed(const Duration(seconds: 2), () {
      SVProgressHUD.dismiss();
      Navigator.of(context).pop();

      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Center(
            child: Text('赠送成功!'),
          ),
          duration: Duration(seconds: 2),
        ),
      );
    });
  }

  void _showBottomSheet(BuildContext context) {
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (BuildContext context) {
        // 在底部弹出视图的顶部放置TabBar
        return SafeArea(
            child: SizedBox(
          height: 364,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Expanded(
                child: DefaultTabController(
                    length: 2,
                    initialIndex: widget.type,
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Container(
                            height: 52,
                            padding: const EdgeInsets.fromLTRB(0, 12, 16, 8),
                            child: const TabBar(
                              isScrollable: true,
                              indicatorSize: TabBarIndicatorSize.label,
                              indicatorColor: Color(0xffFF5E7D),
                              unselectedLabelColor: Color(0xff888888),
                              labelColor: Color(0xffFF5E7D),
                              tabs: [
                                Tab(
                                  text: '猫猫',
                                ),
                                Tab(text: '狗狗'),
                              ],
                            )),
                        Expanded(
                          child: TabBarView(children: [
                            GMAnimaFoodScreen(
                              gmFoodValues: gmFoodValues[1],
                            ),
                            GMAnimaFoodScreen(gmFoodValues: gmFoodValues[2])
                          ]),
                        ),
                      ],
                    )),
              ),
              Container(
                padding: const EdgeInsets.fromLTRB(32, 16, 32, 16),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        const Text(
                          "金币余额：",
                          style:
                              TextStyle(color: Color(0xff333333), fontSize: 12),
                        ),
                        Image.asset(
                          "assets/images/gm_jb_icon@2x.png",
                          width: 18,
                        ),
                        const SizedBox(
                          width: 4,
                        ),
                        Text(
                          '${GMUserManager().user!.coins}',
                          style: const TextStyle(
                              color: Color(0xffFF5E7D),
                              fontSize: 14,
                              fontWeight: FontWeight.w600),
                        ),
                      ],
                    ),
                    const SizedBox(
                      height: 20,
                    ),
                    InkWell(
                      onTap: () {
                        _gmSendFoodToUser();
                      },
                      child: Container(
                        height: 52,
                        alignment: Alignment.center,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(26),
                          color: const Color(0xffFF5E7D),
                        ),
                        child: const Text(
                          "赠送",
                          style: TextStyle(
                              color: Color(0xffffffff),
                              fontSize: 16,
                              fontWeight: FontWeight.w600),
                        ),
                      ),
                    )
                  ],
                ),
              )
            ],
          ),
        ));
      },
    );
  }

  Widget _gmComentTopWidget() {
    // double videoPlayH = ScreenUtil().screenWidth *
    //     double.parse(widget.animaData.files!.first.width!) /
    //     double.parse(widget.animaData.files!.first.height!);
    return Column(
      children: [
        AspectRatio(
          aspectRatio: 3 / 4,
          child: VideoPlayer(_controller),
        ),
        const SizedBox(
          height: 12,
        ),
        ListTile(
          leading: ClipRRect(
            borderRadius: BorderRadius.circular(22),
            child: Image.network(
              'https://file.onepetmall.com/${widget.animaData.url!}',
              width: 44,
              height: 44,
              fit: BoxFit.cover,
            ),
          ),
          title: Text(
            widget.animaData.user!.name!,
            style: const TextStyle(
                color: Color(0xff1a1a1a),
                fontSize: 16,
                fontWeight: FontWeight.w800),
          ),
          subtitle: Text(
            widget.animaData.user!.label!,
            style: const TextStyle(
                color: Color(0xff666666),
                fontSize: 12,
                fontWeight: FontWeight.w200),
          ),
          trailing: InkWell(
            onTap: () {
              _showBottomSheet(context);
            },
            child: Container(
              width: 38,
              height: 38,
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(19),
                color: const Color(0xffFF5E7D),
              ),
              child: Image.asset(
                "assets/images/gm_xq_sl_icon@2x.png",
                width: 16,
              ),
            ),
          ),
        ),
        Container(
          padding: const EdgeInsets.fromLTRB(16, 20, 16, 20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                widget.animaData.text!,
                style: const TextStyle(
                    color: Color(0xff1a1a1a),
                    fontSize: 18,
                    fontWeight: FontWeight.w700),
              ),
              const SizedBox(
                height: 10,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(widget.animaData.tag!,
                      style: const TextStyle(
                          color: Colors.blue,
                          fontSize: 12,
                          fontWeight: FontWeight.w500)),
                  Text(widget.animaData.releaseTime!,
                      style: const TextStyle(
                          color: Color(0xff999999), fontSize: 12))
                ],
              ),
              const SizedBox(
                height: 20,
              ),
              const Divider(
                height: 2,
              ),
              const SizedBox(
                height: 16,
              ),
              Row(
                children: [
                  Container(
                    width: 4,
                    height: 20,
                    decoration: BoxDecoration(
                        color: GMAppUtil.kAppThemColor,
                        borderRadius: BorderRadius.circular(2)),
                  ),
                  const SizedBox(
                    width: 8,
                  ),
                  const Text("互动评论",
                      style: TextStyle(
                          color: Color(0xff1a1a1a),
                          fontSize: 16,
                          fontWeight: FontWeight.w700)),
                ],
              )
            ],
          ),
        )
      ],
    );
  }

  // 回调函数，用于接收从 WidgetB 传递的值
  void onDataReceived(String data) {
    _gmGetComment();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: GMAppUtil.navText(widget.animaData.text!),
        elevation: 0,
        actions: [
          InkWell(
            onTap: () {
              reportAndAddBlack(context);
            },
            child: Image.asset(
              "assets/images/gm_xq_gd_btn.png",
              width: 20,
              height: 20,
            ),
          ),
          const SizedBox(
            width: 12,
          )
        ],
      ),
      body: SafeArea(
          child: Column(
        children: [
          Expanded(
            child: CustomScrollView(
              slivers: [
                SliverToBoxAdapter(
                  child: _gmComentTopWidget(),
                ),
                SliverList(
                  delegate: SliverChildBuilderDelegate(
                    (BuildContext context, int index) {
                      return _gmCommentListWidget(commentArr[index]);
                    },
                    childCount: commentArr.length,
                  ),
                ),
              ],
            ),
          ),
// 底部固定高度的 Container
          GMVideoDetailBottomScreen(
            onDataReceived: onDataReceived,
            videoid: widget.animaData.id!,
          ),
        ],
      )
          // floatingActionButton: FloatingActionButton(
          //   onPressed: () {
          //     setState(() {
          //       _controller.value.isPlaying
          //           ? _controller.pause()
          //           : _controller.play();
          //     });
          //   },
          //   child: Icon(
          //     _controller.value.isPlaying ? Icons.pause : Icons.play_arrow,
          //   ),
          // ),
          ),
    );
  }
}

// ignore: must_be_immutable
class GMAnimaFoodScreen extends StatefulWidget {
  List<Map<String, dynamic>>? gmFoodValues;
  GMAnimaFoodScreen({super.key, required this.gmFoodValues});

  @override
  // ignore: library_private_types_in_public_api
  _GMAnimaFoodScreenState createState() => _GMAnimaFoodScreenState();
}

class _GMAnimaFoodScreenState extends State<GMAnimaFoodScreen> {
  int currentIndex = 0;

  Widget _gmFoodItem(Map<String, dynamic> valueMap, int tag) {
    double gmFoodWH = (ScreenUtil().screenWidth - 32 - 15) * 0.5;
    return InkWell(
      onTap: () {
        currentIndex = tag;
        setState(() {});
      },
      child: Container(
        padding: const EdgeInsets.fromLTRB(12, 20, 12, 12),
        width: gmFoodWH,
        height: gmFoodWH,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          border: Border.all(
            color: currentIndex == tag
                ? const Color(0xffFF5E7D)
                : const Color(0xffEEEEEE), // 设置边框颜色
            width: 1.0, // 设置边框宽度
          ),
        ),
        child: Column(
          children: [
            Expanded(child: Image.asset(valueMap["path"])),
            Row(
              children: [
                Expanded(
                  child: Text(valueMap['name'],
                      style: const TextStyle(
                          color: Color(0xff333333),
                          fontSize: 14,
                          fontWeight: FontWeight.w600)),
                ),
                Image.asset(
                  "assets/images/gm_jb_icon@2x.png",
                  width: 18,
                ),
                const SizedBox(
                  width: 2,
                ),
                Text(
                  '${valueMap['price']}',
                  style: const TextStyle(
                      color: Color(0xffFF5E7D),
                      fontSize: 14,
                      fontWeight: FontWeight.w600),
                )
              ],
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          _gmFoodItem(widget.gmFoodValues!.first, 0),
          _gmFoodItem(widget.gmFoodValues!.last, 1)
        ],
      ),
    );
  }
}

class GMVideoDetailBottomScreen extends StatefulWidget {
  final String videoid;
  final void Function(String) onDataReceived;
  const GMVideoDetailBottomScreen(
      {super.key, required this.onDataReceived, required this.videoid});
  @override
  // ignore: library_private_types_in_public_api
  _GMVideoDetailBottomScreenState createState() =>
      _GMVideoDetailBottomScreenState();
}

class _GMVideoDetailBottomScreenState extends State<GMVideoDetailBottomScreen> {
  bool inCollect = false;
  void _showDi() {
    final TextEditingController gmCommentController = TextEditingController();
    const top = 12.0;
    const txBottom = 40.0;
    const txHeight = 100.0;
    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (ctx) {
        return StatefulBuilder(builder: (ctx2, state) {
          return Container(
            height: MediaQuery.of(ctx2).viewInsets.bottom +
                txHeight +
                top +
                txBottom,
            color: Colors.white,
            child: Stack(
              children: <Widget>[
                Positioned(
                    left: 12,
                    bottom: (MediaQuery.of(ctx2).viewInsets.bottom < 0)
                        ? 0
                        : MediaQuery.of(ctx2).viewInsets.bottom,
                    right: 0,
                    top: top,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: <Widget>[
                            Expanded(
                                child: Container(
                              padding: const EdgeInsets.all(8),
                              height: txHeight,
                              color: const Color(0xffF7F7F7),
                              child: TextField(
                                controller: gmCommentController,
                                cursorColor: const Color(0xff353535), // 设置光标颜色
                                // scrollPadding: EdgeInsets.zero,
                                autofocus: true,
                                maxLines: 4,
                                style: const TextStyle(
                                    fontSize: 15, color: Color(0xff353535)),
                                decoration: const InputDecoration(
                                    contentPadding: EdgeInsets.zero,
                                    isDense: true,
                                    border: InputBorder.none),
                              ),
                            )),
                            InkWell(
                              onTap: () {
                                SVProgressHUD.show();
                                Future.delayed(const Duration(seconds: 2), () {
                                  SVProgressHUD.dismiss();
                                  final text = gmCommentController.text;
                                  widget.onDataReceived(text);
                                  gmCommentController.text = '';
                                  Navigator.pop(context);
                                });
                              },
                              child: Container(
                                padding:
                                    const EdgeInsets.only(left: 12, right: 12),
                                child: const Text("发送",
                                    style: TextStyle(
                                        fontSize: 15,
                                        color: Color(0xffFF803E))),
                              ),
                            ),
                          ],
                        ),
                      ],
                    ))
              ],
            ),
          );
        });
      },
    );
  }

  void _gmNetToCollectVideo() async {
    var response = await GMHttpUtilTwo().post("/cms/publish/collect", data: {
      "id": widget.videoid,
    });
    var jsonStr = json.decode(response.toString());
    int code = jsonStr['status'];
    if (code == 200) {
      inCollect = !inCollect;
      SVProgressHUD.showInfo(status: inCollect ? '已收藏' : "取消收藏");
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: const Color(0xfff1f2f3),
      padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
      height: 49,
      child: Row(
        children: [
          InkWell(
            onTap: () {
              _gmNetToCollectVideo();
            },
            child: Image.asset(
              inCollect
                  ? 'assets/images/gm_xq_sc_s_icon@2x.png'
                  : 'assets/images/gm_xq_sc_n_icon@2x.png',
              width: 24,
            ),
          ),
          const SizedBox(
            width: 25,
          ),
          InkWell(
            onTap: () {
              NativeChannel.shareApp(
                  "https://apps.apple.com/hk/app/tata%E4%BC%B4/id6474584711",
                  'TaTa伴');
            },
            child: Image.asset(
              'assets/images/gm_xq_sx_icon@2x.png',
              width: 20,
            ),
          ),
          const SizedBox(
            width: 25,
          ),
          Expanded(
              child: InkWell(
            onTap: () {
              _showDi();
            },
            child: Container(
              height: 32,
              padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
              decoration: BoxDecoration(
                  color: const Color(0xffffffff),
                  borderRadius: BorderRadius.circular(16)),
              alignment: Alignment.centerLeft,
              child: const Text(
                "我来评论~",
                style: TextStyle(color: Color(0xff999999), fontSize: 14),
              ),
            ),
          ))
        ],
      ),
    );
  }
}
